#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import gettext
import os
import subprocess
import time
import sys
import inspect 
import ConfigParser
from subprocess import Popen, PIPE
from setuptools import setup, find_packages
from setuptools.command.sdist import sdist
from optparse import OptionParser, Option

from Ump import version

def write_config(path,ump_home):
    config = ConfigParser.ConfigParser()
    conf = '%s/Ump/etc/ump.conf'%path.rstrip('/')
    config.read(conf)

#    config.set('imp_main','home',ump_home)
#    config.write(open(conf, "w"))
    row = None
    with open(conf, 'rw') as f:
        for index,tail in enumerate(f):
            if tail.find('home') != -1 and '=' in tail:
                row = index
                break
    if row is not None:
        os.system("sed  -i -e'%dc\home = %s' %s"%(row+1,ump_home,conf))

def install_imp(path,ump_home):
    write_config(path,ump_home)
    cp_to_opt = Popen(['cp','-r',path,'%s'%ump_home], stdout=PIPE)
    stdout, stderr = cp_to_opt.communicate()
    if cp_to_opt.returncode == 0:
        os.chdir('%s/ump/'%ump_home) 
        os.system('python setup.py develop')
    if not cp_to_opt.returncode == 0:
        print >>sys.stderr, stderr
        sys.exit(1)

def install_sqlalchemy(ump_home):
    os.chdir('%s/Ump/tools/sqlalchemy'%ump_home) 
    os.system('python setup.py install  > /dev/null 2>&1 ')

def install_option(ump_home=None):
    path = inspect.getabsfile(install_imp)
    path = '/'.join(path.split('/')[0:-1])
    if ump_home is None :
        write_config(path,'/opt/fusionstack')
    else:
        write_config(path,ump_home)
    install_sqlalchemy(path)

    cp = ConfigParser.ConfigParser()
    cp.read('%s/Ump/etc/ump.conf'%path)
    if ump_home is None:
        try:
            ump_home = cp.get('imp_main', 'home').rstrip('/')
        except Exception,e:
            ump_home = '/opt/fusionstack'
            pass
    ump_home = ump_home.rstrip('/')
    
    if not os.path.exists('%s/log/ump'%ump_home):
        os.system('mkdir %s/log/ump -p'%ump_home)

    p1 = Popen(['pwd'], stdout=PIPE)
    stdout, stderr = p1.communicate()
    if p1.returncode == 0:
        if stdout.strip() != '%s/ump'%ump_home:
            if os.path.exists('%s/ump/'%ump_home):
                if os.getcwd().startswith('%s/ump/'%ump_home):
                    os.chdir('%s/ump/'%ump_home)
                    os.system('python setup.py develop')
                else:
                    install_imp(path,ump_home)
            else:
                install_imp(path,ump_home)
            if not p1.returncode == 0:
                print >>sys.stderr, stderr
                sys.exit(1)
        else:
            os.chdir('%s/ump/'%ump_home) 
            os.system('python setup.py develop')

        
    
    if not p1.returncode == 0:
        print >>sys.stderr, stderr
        sys.exit(1)


def main(): 
    usage = 'usage: %prog -C PATH'
    parser = OptionParser(usage=usage)
    parser.add_option("-C", "--path",
            help="ump install path directory DIR"),
    (options, args) = parser.parse_args()
    path = options.path

    if path is None:
        install_option()
    else:
        install_option(path)

    #    parser.print_help()
    #    sys.exit(1)

if __name__ == "__main__":
    main()
